# coding=utf-8
import uuid
import argparse
import os


def load_notes(filename):
    """
    Load notes from a file.
    :param filename: The name of the file to load notes from.
    :return: A list of notes.
    """
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            notes = []
            rows = file.readlines()
            for row in rows:
            # :
                if row.startswith('#'):
                    continue
                c1, c2 = row.split('||')
                notes.append((c1.strip(), c2.strip()))
                # if c1 == c2:
        return notes
            # return [note.strip() for note in notes]
    except FileNotFoundError:
        print(f"File not found: {filename}")
        return []
    except Exception as e:
        print(f"Error loading notes: {e}")
        return []


TEMPL = """#separator:tab
#html:true
#columns:Id\tNoteType\tDeck\tFront\tBack
#guid column:1
#notetype column:2
#deck column:3
"""


TEMPL2 = """{ID}\t{NOTE_TYPE}\t{DECK}\t{FRONT}\t{BACK}
"""


def export_notes(notes, filename, note_type="Basic (and reversed card)", deck="Default"):
    """
    Export notes to a file.
    :param notes: A list of notes to export.
    :param filename: The name of the file to export notes to.
    :param note_type: The type of note for Anki.
    :param deck: The name of the deck for the notes.
    """
    try:
        with open(filename, 'w', encoding='utf-8') as file:
            file.write(TEMPL)

            for note in notes:
                rec = {
                    'ID': str(uuid.uuid4()),
                    'NOTE_TYPE': note_type,
                    'DECK': deck,
                    'FRONT': note[0],
                    'BACK': note[1]
                }
                file.write(TEMPL2.format(**rec))
    except Exception as e:
        print(f"Error exporting notes: {e}")


def main():
    # 创建命令行参数解析器
    parser = argparse.ArgumentParser(description='Convert notes to Anki import format')
    parser.add_argument('input', help='Input file name (required)')
    parser.add_argument('-o', '--output', help='Output file name (default: input filename + _notes suffix)')
    parser.add_argument('-n', '--note-type', default='Basic (and reversed card)', help='Note type (default: Basic (and reversed card))')
    parser.add_argument('-d', '--deck', default='Default', help='Deck name (default: Default)')
    
    # 解析命令行参数
    args = parser.parse_args()
    
    # 如果没有指定输出文件名，生成默认的输出文件名
    if args.output is None:
        input_name, input_ext = os.path.splitext(args.input)
        args.output = f"{input_name}_notes{input_ext}"
    
    print(f"Input file: {args.input}")
    print(f"Output file: {args.output}")
    print(f"Note type: {args.note_type}")
    print(f"Deck: {args.deck}")
    
    # 加载和处理笔记
    notes = load_notes(args.input)
    if notes:
        print(f"Loaded {len(notes)} notes:")
        for c1, c2 in notes:
            print(f"Front: {c1}, Back: {c2}")
        export_notes(notes, args.output, args.note_type, args.deck)
        print(f"Notes exported to {args.output}")
    else:
        print("No notes loaded.")


if __name__ == "__main__":
    # import sys
    # from pathlib import Path

    # # Ensure the script is run from the correct directory
    # current_path = Path(__file__).resolve().parent
    # sys.path.append(str(current_path))

    # # Import and run the main application
    # from app import main
    main()